import React, { Component, useRef, useState } from 'react';
import {
  FlatList, StyleSheet, SafeAreaView, TouchableOpacity, View
} from 'react-native';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { Tip, Dialog, Input } from 'beeshell';
import { Chart } from '../../components';
import Http from '../../service/http';
import requestCheck from '../../utils/RequestCheckUtil';
import DataUtil from '../../utils/DataUtil';
import { theme } from '../../constants';
import { colors } from '../../constants/theme';
import { getInfo } from '../../service/token';
import ChartConfig from '../../configs/ChartConfig.json';

function TaskWarning({ navigation }) {
  const { state: { params: { instanceId, processName } } } = navigation;
  const dialog = useRef(null);
  const [input, setInput] = useState('');
  const handleWarning = () => {
    if (!instanceId) {
      Tip.show('初始化中');
    } else {
      dialog.current.open();
    }
  };

  const sendMsg = async () => {
    const { aud } = await getInfo();
    const res = await Http.sendMessage({
      from: aud,
      ecnId: instanceId,
      message: {
        content: input,
        process: processName
      }
    });
    const callback = () => Tip.show('发送成功');
    requestCheck(res, callback, navigation);
    setInput('');
  };

  return (
    <>
      <TouchableOpacity style={{ marginRight: theme.sizes.base }} onPress={handleWarning}>
        <AntDesign name="warning" size={26} color="white" />
      </TouchableOpacity>
      <Dialog
        ref={dialog}
        offsetY={-100}
        title="发送消息"
        body={(
          <View style={{ backgroundColor: '#fff', padding: 20 }}>
            <Input
              textAlign="left"
              style={{
                height: 100,
                borderColor: colors.gray,
                borderWidth: 1,
              }}
              multiline
              value={input}
              placeholder="请输入消息"
              onChange={(value) => { setInput(value); }}
            />
          </View>
          )}
        cancelable
        operationsLayout="row"
        operations={[
          {
            labelText: '取消',
            type: 'cancel',
            onPress: () => setInput('')
          },
          {
            labelText: '发送消息',
            type: 'confirm',
            onPress: sendMsg
          },
        ]}
      />
    </>
  );
}

export default class ProcessMonitor extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerRight: () => <TaskWarning navigation={navigation} />
  })

  constructor(props) {
    super(props);
    this.chartsRef = [];
    this.state = {
      dataSource: [],
    };
    this.lastData = [];
  }

  async componentDidMount() {
    await this.fetchData();
    this.interval = setInterval(async () => {
      await this.fetchData();
      const { dataSource } = this.state;
      this.chartsRef.forEach((chart, index) => {
        const al = ChartConfig[dataSource[index].name];
        chart.setOption({
          title: {
            text: al && al.name
          },
          series: dataSource[index].series
        });
      });
    }, 5000);
  }

  componentWillUnmount() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  }

  fetchData = async () => {
    const { navigation: { state: { params: { historyId, taskId } } } } = this.props;
    const { navigation } = this.props;
    const res = await Http.inquireHistoryTask({ historyId, taskId });
    const callback = (data) => {
      const { arguments: args, taskStatus, instance } = data;
      DataUtil.appendData(this.lastData, args);
      this.setState(
        {
          dataSource: DataUtil.convertDataForChart(args),
        }
      );
      navigation.setParams({ instanceId: instance });
      this.lastData = args;
      // TODO 是否清除计时器
      // if (taskStatus === 2 && this.interval) {
      //   clearInterval(this.interval);
      // }
    };
    requestCheck(res, callback, navigation);
  }

  render() {
    const { dataSource } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <FlatList
          data={dataSource}
          renderItem={({ item, index }) => (
            <Chart
              type={item.type}
              key={index}
              ref={(el) => { this.chartsRef[index] = el; }}
            />
          )}
          keyExtractor={(item) => item.name}
        />
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  }
});
